package com.rw.rule.readWrite;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.rw.database.ReadWriteDataSource;
import com.rw.rule.ReadWriteRule;

/**
 * spring读写分离规则，给予spring事物实现,spring事物管理需要结合延迟加载事物源实现相关功能
 * org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
 * 
 * @author lkclkc88(lkclkc88@sina.com)
 * @Date 2016年1月27日
 */

public class SpringReadWriteRule implements ReadWriteRule {

	private Logger log = LoggerFactory.getLogger(SpringReadWriteRule.class);

	@Override
	public boolean isRead(ReadWriteDataSource dataSource) {
		/**
		 * 判断spring的事物，如果事物为只读，返回FALSE，否者返回TRUE
		 */
		boolean read = TransactionSynchronizationManager
				.isCurrentTransactionReadOnly();
		if (read) {
			if (log.isDebugEnabled()) {
				log.debug("*************** return slave dataSouce*****************");
			}
			return true;
		}
		if (log.isDebugEnabled()) {
			log.debug("**************** return master dataSouce******************");
		}
		return false;
	}
}
